﻿using System;
using System.Web;
using System.Collections.Generic;
using Token.Piker.BLL;
using Token.Piker.Model;
using System.Data;
using System.Linq;
using Token.Util;

namespace Token.Piker.Web.AJAX
{
    /// <summary>
    /// Single 的摘要说明
    /// </summary>
    public class Single : IHttpHandler
    {

        PhotoBLL singlePhoto = new PhotoBLL();

        class ImgInfo
        {
            private string id_person;

            public string Id_person
            {
                get { return id_person == "undefined" ? string.Empty : id_person; }
                set { id_person = value; }
            }

            private string id_img;

            public string Id_img
            {
                get { return id_img; }
                set { id_img = value; }
            }

            public string success;
        }
        class imglistInfo
        {
            private List<Photo> imgList;
            public List<Photo> ImgList
            {
                get { return imgList; }
                set { imgList = value; listcount = imgList.Count; }
            }
            private int listcount;
            public int Listcount
            {
                get { return listcount; }
            }
        }

        class PcommentInfo
        {
            private Pcomment _pcomment;
            public Pcomment PComment
            {
                get { return _pcomment; }
                set { _pcomment = value; }
            }
            private string _username;
            public string UserName
            {
                get { return _username; }
                set { _username = value; }
            }
            private string _userpic;
            public string UserPic
            {
                get { return _userpic; }
                set { _userpic = value; }
            }
        }

        class AcommentInfo
        {
            private Acomment _acomment;
            public Acomment AComment
            {
                get { return _acomment; }
                set { _acomment = value; }
            }
            private string _username;
            public string UserName
            {
                get { return _username; }
                set { _username = value; }
            }
            private string _userpic;
            public string UserPic
            {
                get { return _userpic; }
                set { _userpic = value; }
            }
            public string success;
        }

        public void ProcessRequest(HttpContext context)
        {
            object fun_id = context.Request["f_id"];  //读取方法标识
            context.Response.ContentType = "text/plain";
            //大图预加载
            if (fun_id != null && fun_id.ToString() == "SLI")
            {
                object img_pre = context.Request.Params["imgInfo_pre"];  //读取参数
                object img_cur = context.Request["imgInfo_cur"];  //读取参数
                object img_next = context.Request["imgInfo_next"];  //读取参数
                context.Response.Write(JsonHelper.Serialize(ShowLargeImg(img_pre, img_cur, img_next)));
            }
            //缩略图预加载
            if (fun_id != null && fun_id.ToString() == "PLI")
            {
                object cur_index = context.Request["curImg_index"];  //读取参数
                object scroll_way = context.Request["way"];  //读取参数
                int curindex;
                if (Int32.TryParse(cur_index.ToString(), out curindex))
                {
                    if (scroll_way.ToString() == "L")
                    {
                        context.Response.Write(JsonHelper.Serialize(PreLoadImg(curindex, scroll_way.ToString())));
                    }
                    else if (scroll_way.ToString() == "R")
                    {
                        imglistInfo imgList = new imglistInfo();
                        imgList.ImgList = PreLoadImg(curindex, scroll_way.ToString());
                        context.Response.Write(JsonHelper.Serialize(imgList));
                    }
                }
            }
            //提交图片评论
            if (fun_id != null && fun_id.ToString() == "SCO")
            {
                object photo_id = context.Request["Photo_ID"];  //读取参数
                object user_id = context.Request["User_ID"];  //读取参数
                object content = context.Request["Content"];  //读取参数
                context.Response.Write(JsonHelper.Serialize(SubmitComment(photo_id, user_id, content)));
            }

            //图片评论加载
            if (fun_id != null && fun_id.ToString() == "PCB")
            {
                object photo_id = context.Request["photo_ID"];  //读取参数
                List<PcommentInfo> pcomment = PcommentBind(Int32.Parse(photo_id.ToString()));
                context.Response.Write(JsonHelper.Serialize(pcomment));
            }
            //图片喜欢
            if (fun_id != null && fun_id.ToString() == "SLN")
            {
                object photo_id = context.Request["photo_ID"];  //读取参数
                object user_id = context.Request["user_ID"];  //读取参数
                if (photo_id != null && photo_id.ToString() != "" && user_id != null && user_id.ToString() != "")
                {
                    context.Response.Write(JsonHelper.Serialize(SubmitLikeNum(int.Parse(photo_id.ToString()), int.Parse(user_id.ToString()))));
                }
                else
                {
                    ImgInfo img = new ImgInfo();
                    img.success = "false";
                    context.Response.Write(JsonHelper.Serialize(img));
                }
            }
            //用户名
            if (fun_id != null && fun_id.ToString() == "GUN")
            {
                object user_id = context.Request["UserID"];  //读取参数
                string name = GetUserName(user_id);
                context.Response.Write(JsonHelper.Serialize(name));
            }
            //提交相册评论
            if (fun_id != null && fun_id.ToString() == "ACO")
            {
                object album_id = context.Request["Album_ID"];  //读取参数
                object user_id = context.Request["User_ID"];  //读取参数
                object content = context.Request["Content"];  //读取参数
                context.Response.Write(JsonHelper.Serialize(SubmitAComment(album_id, user_id, content)));
            }

            //相册评论加载
            if (fun_id != null && fun_id.ToString() == "ACB")
            {
                object album_id = context.Request["Album_ID"];  //读取参数
                List<AcommentInfo> acomment = AcommentBind(Int32.Parse(album_id.ToString()));
                context.Response.Write(JsonHelper.Serialize(acomment));
            }
        }

        //提交图片评论
        private ImgInfo SubmitComment(object photo_id, object user_id, object content)
        {
            ImgInfo imginfo = new ImgInfo();
            if (photo_id != null && user_id != null)
            {
                PcommentBLL pcommenBLL = new PcommentBLL();
                Pcomment pcomment = new Pcomment();
                pcomment.PhotoID = Int32.Parse(photo_id.ToString());
                pcomment.UserID = Int32.Parse(user_id.ToString());
                pcomment.Content = content.ToString();
                pcomment.CommentTime = DateTime.Now;
                pcomment.Flag = 0;
                try
                {
                    pcommenBLL.Add(pcomment);
                    imginfo.Id_img = photo_id.ToString();
                    imginfo.success = "true";
                    return imginfo;
                }
                catch
                {
                    imginfo.success = "false";
                    return imginfo;
                }
            }
            else
            {
                imginfo.success = "false";
                return imginfo;
            }
        }
        //提交相册评论
        private AcommentInfo SubmitAComment(object album_id, object user_id, object content)
        {
            AcommentInfo acoinfo = new AcommentInfo();
            if (album_id != null && user_id != null)
            {
                AcommentBLL acommenBLL = new AcommentBLL();
                Acomment acomment = new Acomment();
                acomment.AlbumID = Int32.Parse(album_id.ToString());
                acomment.UserID = Int32.Parse(user_id.ToString());
                acomment.Content = content.ToString();
                acomment.CommentTime = DateTime.Now;
                acomment.Flag = 0;
                try
                {
                    acommenBLL.Add(acomment);
                    //acoinfo.UserName = GetUserName(user_id);
                    acoinfo.success = "true";
                    return acoinfo;
                }
                catch
                {
                    acoinfo.success = "false";
                    return acoinfo;
                }
            }
            else
            {
                acoinfo.success = "false";
                return acoinfo;
            }
        }
        //喜欢
        private ImgInfo SubmitLikeNum(int PID, int UID)
        {
            ImgInfo img = new ImgInfo();
            try
            {
                PhotoLikeBLL photolikeBll = new PhotoLikeBLL();
                PhotoLike photolike = photolikeBll.GetModelByIDs(PID, UID);
                if (photolike != null && photolike.Id != 0)
                {
                    img.Id_img = "0";
                    img.success = "false";
                    return img;
                }
                else
                {
                    //更改photo表中的LikeCount
                    Photo photo = singlePhoto.GetModel(PID);
                    photo.LikeCount += 1;
                    singlePhoto.Update(photo);
                    //增加PhotoLike记录
                    photolike = new PhotoLike();
                    photolike.PhotoID = PID;
                    photolike.UserID = UID;
                    photolike.LikeTime = DateTime.Now;
                    photolike.Flag = 1;
                    photolikeBll.Add(photolike);
                    //返回信息
                    img.Id_img = photo.LikeCount.ToString();
                    img.success = "true";
                    return img;
                }
            }
            catch
            {
                img.success = "false";
                return img;
            }
        }
        //获取图片对应评论
        private List<PcommentInfo> PcommentBind(int ID)
        {
            PcommentBLL pcommenBLL = new PcommentBLL();
            string strwhere = " PhotoID=" + ID + "and Flag!=1 order by CommentTime desc";
            DataSet pc = pcommenBLL.GetList(strwhere);
            List<Pcomment> pcomment = DataSetToIList<Pcomment>(pc, 0);
            List<PcommentInfo> pcommentInfo = new List<PcommentInfo>();
            foreach (Pcomment P in pcomment)
            {
                PcommentInfo tpc = new PcommentInfo();
                tpc.PComment = P;
                User user = GetUser(P.UserID);
                string name = user.UserName;
                tpc.UserPic = user.UserPic;
                tpc.UserName = name == null || name.ToString() == "" || name.ToString() == "null" ? "游客" : name;
                pcommentInfo.Add(tpc);
            }
            return pcommentInfo;
        }
        //获取相册对应评论
        private List<AcommentInfo> AcommentBind(int ID)
        {
            AcommentBLL acommenBLL = new AcommentBLL();
            string strwhere = " AlbumID=" + ID + " and Flag!=1 order by CommentTime desc";
            DataSet ac = acommenBLL.GetList(strwhere);
            List<Acomment> acomment = DataSetToIList<Acomment>(ac, 0);
            List<AcommentInfo> acommentInfo = new List<AcommentInfo>();
            foreach (Acomment A in acomment)
            {
                AcommentInfo tpc = new AcommentInfo();
                tpc.AComment = A;
                User user = GetUser(A.UserID);
                string name = user.UserName;
                tpc.UserPic = user.UserPic;
                tpc.UserName = name == null || name.ToString() == "" || name.ToString() == "null" ? "游客" : name;
                acommentInfo.Add(tpc);
            }
            return acommentInfo;
        }
        //显示、预加载大图
        private List<Photo> ShowLargeImg(object img_pre, object img_cur, object img_next)
        {
            ImgInfo imgInfo_pre = (img_pre == null || img_pre.ToString() == "undefined") ? null : JsonHelper.Deserialize<ImgInfo>(img_pre.ToString().Replace("undefined", "\"\""));
            ImgInfo imgInfo_cur = (img_cur == null || img_cur.ToString() == "undefined") ? null : JsonHelper.Deserialize<ImgInfo>(img_cur.ToString().Replace("undefined", "\"\""));
            ImgInfo imgInfo_next = (img_next == null || img_next.ToString() == "undefined") ? null : JsonHelper.Deserialize<ImgInfo>(img_next.ToString().Replace("undefined", "\"\""));

            List<Photo> ImgList = new List<Photo>(3);
            Photo imgLarge_pre = new Photo();
            Photo imgLarge_cur = new Photo();
            Photo imgLarge_next = new Photo();
            if (imgInfo_pre != null && imgInfo_pre.Id_img != null && imgInfo_pre.Id_img != "")
            {
                imgLarge_pre = singlePhoto.GetModel(Convert.ToInt32(imgInfo_pre.Id_img));
            }
            if (imgInfo_cur != null && imgInfo_cur.Id_img != null && imgInfo_cur.Id_img != "")
            {
                imgLarge_cur = singlePhoto.GetModel(Convert.ToInt32(imgInfo_cur.Id_img));
            }
            if (imgInfo_next != null && imgInfo_next.Id_img != null && imgInfo_next.Id_img != "")
            {
                imgLarge_next = singlePhoto.GetModel(Convert.ToInt32(imgInfo_next.Id_img));
            }
            ImgList.Insert(0, imgLarge_pre);
            ImgList.Insert(1, imgLarge_cur);
            ImgList.Insert(2, imgLarge_next);
            return ImgList;
        }

        //预加载缩略图
        private List<Photo> PreLoadImg(int cur_index, string scrollWay)
        {
            int ImgNum = singlePhoto.GetRecordCount("");
            List<Photo> img_list = new List<Photo>();
            if (scrollWay == "L")
            {
                if (ImgNum > 12)
                {
                    if (ImgNum - cur_index - 4 > 0 && ImgNum - cur_index - 4 < 4)
                    {
                        img_list = DataSetToIList<Photo>(singlePhoto.GetListByPage("", "ID", cur_index + 5, ImgNum), 0);
                    }
                    else if (ImgNum - cur_index >= 4)
                    {
                        img_list = DataSetToIList<Photo>(singlePhoto.GetListByPage("", "ID", cur_index + 5, cur_index + 8), 0);
                    }
                }
                Photo img_temp = new Photo();
                img_temp.ID = 0; img_temp.CompressUrl_4 = "images/default.jpg";
                for (int i = img_list.Count; i < 4; i++)
                {
                    img_list.Insert(i, img_temp);
                }
            }
            else if (scrollWay == "R")
            {
                if (cur_index > 4)
                {
                    img_list = DataSetToIList<Photo>(singlePhoto.GetListByPage("", "ID", cur_index - 4, cur_index - 1), 0);
                }
                else if (cur_index <= 4 && cur_index > 1)
                {
                    img_list = DataSetToIList<Photo>(singlePhoto.GetListByPage("", "ID", 1, cur_index - 1), 0);
                }
                else if (cur_index <= 1)
                {
                    img_list = new List<Photo>();
                }
            }
            return img_list;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string GetUserName(object User_ID)
        {
            //绑定用户名
            UserBLL UserBll = new UserBLL();
            User pikerUser = new User();
            pikerUser = UserBll.GetModel(Int32.Parse(User_ID == null || User_ID.ToString() == "null" ? "0" : User_ID.ToString()));
            return pikerUser == null ? "" : pikerUser.UserName;
            //context.Response.ContentType = "text/plain";
            //context.Response.Write(JsonHelper.Serialize(SubmitComment(photo_id, user_id, content)));
        }
        private User GetUser(object User_ID)
        {
            //绑定用户名
            UserBLL UserBll = new UserBLL();
            User pikerUser = new User();
            pikerUser = UserBll.GetModel(Int32.Parse(User_ID == null || User_ID.ToString() == "null" ? "0" : User_ID.ToString()));
            return pikerUser == null ? new User() : pikerUser;
            //context.Response.ContentType = "text/plain";
            //context.Response.Write(JsonHelper.Serialize(SubmitComment(photo_id, user_id, content)));
        }

        /// <summary>   
        /// DataSet装换为泛型集合   
        /// </summary>   
        /// <typeparam name="T"></typeparam>   
        /// <param name="p_DataSet">DataSet</param>   
        /// <param name="p_TableIndex">待转换数据表索引</param>   
        /// <returns></returns>   
        /// 2008-08-01 22:46 HPDV2806   
        public static List<T> DataSetToIList<T>(DataSet p_DataSet, int p_TableIndex)
        {
            if (p_DataSet == null || p_DataSet.Tables.Count < 0)
                return null;
            if (p_TableIndex > p_DataSet.Tables.Count - 1)
                return null;
            if (p_TableIndex < 0)
                p_TableIndex = 0;

            DataTable p_Data = p_DataSet.Tables[p_TableIndex];
            // 返回值初始化   
            List<T> result = new List<T>();
            for (int j = 0; j < p_Data.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                System.Reflection.PropertyInfo[] propertys = _t.GetType().GetProperties();
                foreach (System.Reflection.PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < p_Data.Columns.Count; i++)
                    {
                        // 属性与字段名称一致的进行赋值   
                        if (pi.Name.Equals(p_Data.Columns[i].ColumnName))
                        {
                            // 数据库NULL值单独处理   
                            if (p_Data.Rows[j][i] != DBNull.Value)
                                pi.SetValue(_t, p_Data.Rows[j][i], null);
                            else
                                pi.SetValue(_t, null, null);
                            break;
                        }
                    }
                }
                result.Add(_t);
            }
            return result;
        }
    }
}